<template>
  <a-modal 
    v-model:visible="visible"
    :title="isLoginMode ? 'Login' : 'Register'"
    :width="isLoginMode ? 600:1000"
    :footer="false"
    @cancel="handleCancel"
    :mask-closable="false"
  >
    <div class="flex items-start pt-2 pb-4">
      <!-- 头像占位符 -->
      <div class="w-[103px] mx-8 flex items-center justify-center overflow-hidden self-start">
        <img v-if="isLoginMode" src="@/assets/images/login-avatar.png" alt="Avatar" class="w-full h-full object-cover" />
        <div v-else>
          <a-upload
            action="/"
            :fileList="avatar ? [avatar] : []"
            :show-file-list="false"
            @change="onChange"
            @progress="onProgress"
          >
            <template #upload-button>
              <div
                :class="`arco-upload-list-item${
                  avatar && avatar.status === 'error' ? ' arco-upload-list-item-error' : ''
                }`"
              >
                <div
                  class="arco-upload-list-picture custom-upload-avatar !w-[100px] !h-[100px] !rounded-full !m-0"
                  v-if="avatar && avatar.url"
                >
                  <img :src="avatar.url" />
                  <div class="arco-upload-list-picture-mask">
                    <IconEdit />
                  </div>
                  <a-progress
                    v-if="avatar.status === 'uploading' && avatar.percent < 100"
                    :percent="avatar.percent"
                    type="circle"
                    size="mini"
                    :style="{
                      position: 'absolute',
                      left: '50%',
                      top: '50%',
                      transform: 'translateX(-50%) translateY(-50%)',
                    }"
                  />
                </div>
                <div v-else class="flex flex-col items-center justify-center h-full">
                  <img src="@/assets/images/login-avatar.png" alt="Avatar" class="w-full h-full object-cover" />
                  <a-button type="primary" class="text-center">Upload</a-button>
                  <!-- <div class="arco-upload-picture-card-text">
                    <IconPlus />
                    <div style="margin-top: 10px; font-weight: 600">Upload</div>
                  </div> -->
                </div>
              </div>
            </template>
          </a-upload>
        </div>
      </div>

      <!-- 表单容器 -->
      <div class="flex-grow">
        <!-- 登录表单 -->
        <a-form 
          v-if="isLoginMode"
          :model="loginForm" 
          :rules="loginRules" 
          @submit="handleLogin"
          layout="vertical"
          class="w-full"
        >
        <!-- Email 字段 -->
        <a-form-item field="email" label="Email" class="mb-4">
          <a-input 
            v-model="loginForm.email" 
            placeholder="Please enter your email address."
            size="large"
            class="w-full"
          />
        </a-form-item>
        
        <!-- 密码字段 -->
        <a-form-item field="password" label="Password" class="mb-6">
          <a-input-password 
            v-model="loginForm.password" 
            placeholder="Please enter your password."
            size="large"
            class="w-full"
          />
        </a-form-item>
        
        <!-- 登录按钮 -->
        <a-button 
          type="primary" 
          html-type="submit" 
          :loading="loading"
          long
          size="large"
          class="bg-blue-600 hover:bg-blue-700 transition-all duration-300 shadow-md hover:shadow-lg rounded-lg"
        >
          Login
        </a-button>
        
        <!-- 忘记密码和注册链接 -->
        <div class="flex justify-center items-center mt-4 space-x-4">
          <a-button type="text" @click="showForgotPassword = true" class="text-sm text-gray-500 hover:text-blue-600">
            Forgot password?
          </a-button>
          <a-button type="text" @click="isLoginMode = false" class="text-sm text-gray-500 hover:text-blue-600">
            Register
          </a-button>
        </div>
      </a-form>

      <!-- 注册表单 -->
      <a-form
        v-else
        :model="registerForm"
        :rules="registerRules"
        @submit="handleRegister"
        layout="vertical"
        class="w-full"
      >
        <a-divider orientation="left">
          <div class="font-bold">Contact Information</div>
        </a-divider>
        <a-row :gutter="24">
          <a-col :span="12">
            <!-- Email 字段 -->
            <a-form-item field="email" label="Email" class="mb-4">
              <a-input
                v-model="registerForm.email"
                placeholder="Email"
                size="large"
                class="w-full"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="profile.nickName" label="Nickname" class="mb-4">
              <a-input
                v-model="registerForm.profile.nickName"
                size="large"
              />
              <a-button 
                @click="generateNickname"
                size="large"
                type="outline"
                class="ml-2"
              >
                random
              </a-button>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item field="profile.firstName" label="First Name" class="mb-4">
              <a-input
                v-model="registerForm.profile.firstName"
                placeholder="First Name"
                size="large"
                class="w-full"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="profile.lastName" label="Last Name" class="mb-4">
              <a-input
                v-model="registerForm.profile.lastName"
                placeholder="Last Name"
                size="large"
                class="w-full"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item field="profile.gender" label="Gender" class="mb-4">
          <a-radio-group v-model="registerForm.profile.gender">
            <a-radio value="male">
              <template #radio="{ checked }">
                <icon-man 
                  style="stroke-width: 5" 
                  :class="`!w-[25px] !h-[25px] !p-[4px] bg-primary rounded-full !text-white mr-2 ${checked ? 'opacity-100' : 'opacity-50'}`"
                />Male
              </template>
            </a-radio>
            <a-radio value="female">
              <template #radio="{ checked }">
                <icon-woman 
                  style="stroke-width: 5" 
                  :class="`!w-[25px] !h-[25px] !p-[4px] bg-primary rounded-full !text-white mr-2 ${checked ? 'opacity-100' : 'opacity-50'}`"
                />Female
              </template>
            </a-radio>
            <a-radio value="secret">
              <template #radio="{ checked }">
                <icon-lock 
                  style="stroke-width: 5" 
                  :class="`!w-[25px] !h-[25px] !p-[4px] bg-primary rounded-full !text-white mr-2 ${checked ? 'opacity-100' : 'opacity-50'}`"
                />Secret
              </template>
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item field="profile.location.country" label="Country" class="mb-4">
              <a-select
                v-model="registerForm.profile.location.country"
                placeholder="Select a country"
                size="large"
                class="w-full"
              >
                <a-option value="us">United States</a-option>
                <a-option value="ca">Canada</a-option>
                <a-option value="gb">United Kingdom</a-option>
                <a-option value="au">Australia</a-option>
                <a-option value="other">Other</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="profile.location.city" label="City" class="mb-4">
              <a-input
                v-model="registerForm.profile.location.city"
                placeholder="City"
                size="large"
                class="w-full"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-divider orientation="left">
          <div class="font-bold">Professional Information</div>
        </a-divider>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item field="affiliation.type" label="Institution Type" class="mb-4">
              <a-select
                v-model="registerForm.affiliation.type"
                placeholder="Select a institution type"
                size="large"
                class="w-full"
              >
                <a-option value="hospital">Hospital</a-option>
                <a-option value="school">School</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="affiliation.name" label="Institution Name" class="mb-4">
              <a-input
                v-model="registerForm.affiliation.name"
                placeholder="Institution Name"
                size="large"
                class="w-full"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-divider orientation="left">
          <div class="font-bold">Account Information</div>
        </a-divider>
        <a-row :gutter="24">
          <a-col :span="12">
            <!-- 密码字段 -->
            <a-form-item field="password" label="Password" class="mb-4">
              <a-input-password
                v-model="registerForm.password"
                placeholder="Please enter your password."
                size="large"
                class="w-full"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <!-- 确认密码字段 -->
            <a-form-item field="confirmPassword" label="Confirm Password" class="mb-6">
              <a-input-password
                v-model="registerForm.confirmPassword"
                placeholder="Please enter your password again."
                size="large"
                class="w-full"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <!-- 验证码字段 -->
        <a-form-item field="veryCode" label="Verification Code" class="mb-4">
          <div class="flex space-x-2">
            <a-input
              v-model="registerForm.veryCode"
              placeholder="Verification Code"
              size="large"
              class="flex-1"
            />
            <a-button
              @click="sendCode"
              :loading="codeLoading"
              :disabled="codeCountdown > 0"
              size="large"
              class="w-32"
            >
              {{ resetCodeCountdown > 0 ? `Resend in ${resetCodeCountdown} seconds` : 'Send' }}
            </a-button>
          </div>
        </a-form-item>
        <!-- 注册按钮 -->
        <a-button
          type="primary"
          html-type="submit"
          :loading="loading"
          long
          size="large"
          class="bg-blue-600 hover:bg-blue-700 transition-all duration-300 shadow-md hover:shadow-lg rounded-lg"
        >
          Register
        </a-button>

        <!-- 返回登录 -->
        <div class="text-center mt-4">
          <a-button type="text" @click="isLoginMode = true" class="text-sm text-gray-500 hover:text-blue-600">
            Return to login
          </a-button>
        </div>
      </a-form>
      </div>
    </div>
  </a-modal>
  
  <!-- 忘记密码弹窗 -->
  <a-modal 
    v-model:visible="showForgotPassword" 
    title="Reset your password" 
    :width="400"
    :footer="false"
  >
    <a-form 
      :model="resetForm" 
      :rules="resetRules" 
      @submit="handleResetPassword"
      layout="vertical"
    >
      <a-form-item field="email" label="Email">
        <a-input 
          v-model="resetForm.email" 
          placeholder="Please enter your email address."
          size="large"
        />
      </a-form-item>
      
      <a-form-item field="veryCode" label="Verification Code">
        <a-input-group>
          <a-input 
            v-model="resetForm.veryCode" 
            placeholder="Verification Code"
            size="large"
          />
          <a-button 
            @click="sendResetCode" 
            :loading="resetCodeLoading"
            :disabled="resetCodeCountdown > 0"
            size="large"
          >
            {{ resetCodeCountdown > 0 ? `Resend in ${resetCodeCountdown} seconds` : 'Send' }}
          </a-button>
        </a-input-group>
      </a-form-item>
      
      <a-form-item field="newPassword" label="New password">
        <a-input-password 
          v-model="resetForm.newPassword" 
          placeholder="Please enter your new password."
          size="large"
        />
      </a-form-item>
      
      <a-form-item>
        <a-button 
          type="primary" 
          html-type="submit" 
          :loading="resetLoading"
          long
          size="large"
        >
          Reset password
        </a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import { useUserStore } from '@/stores/user'
import { sendVerificationCodeApi, resetPasswordApi } from '@/api/auth'
import { useRouter } from 'vue-router'
import { generateRandomNickname } from '@/utils/tool'

interface Props {
  visible: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'loginSuccess'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const userStore = useUserStore()

const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const isLoginMode = ref(true)
const loading = ref(false)
const showForgotPassword = ref(false)

// 登录表单
const loginForm = reactive({
  email: '',
  password: ''
})

// 注册表单
const registerForm = reactive({
  email: '',
  password: '',
  confirmPassword: '',
  veryCode: '',
  profile: {
    nickName: '',
    firstName: '',
    lastName: '',
    gender: '',
    avatar: '',
    location: {
      country: '',
      city: ''
    }
  },
  affiliation: {
    type: '',
    name: '',
  },
  expert_info: []
})

const avatar = ref()

// 重置密码表单
const resetForm = reactive({
  email: '',
  veryCode: '',
  newPassword: ''
})

// 验证码相关
const codeLoading = ref(false)
const codeCountdown = ref(0)
const resetCodeLoading = ref(false)
const resetCodeCountdown = ref(0)
const resetLoading = ref(false)

// 表单验证规则
const loginRules = {
  email: [
    { required: true, message: 'Please enter your email address.' }
  ],
  password: [
    { required: true, message: 'Please enter your password.' }
  ]
}

const registerRules = {
  email: [
    { required: true, message: 'Please enter your email address.' }
  ],
  'profile.nickName': [
    { required: true, message: 'Please enter your nickname.' }
  ],
  'profile.firstName': [
    { required: true, message: 'Please enter your first name.' }
  ],
  'profile.lastName': [
    { required: true, message: 'Please enter your last name.' }
  ],
  'profile.gender': [
    { required: true, message: 'Please enter your gender.' }
  ],
  'profile.location.country': [
    { required: true, message: 'Please enter your country.' }
  ],
  'profile.location.city': [
    { required: true, message: 'Please enter your city.' }
  ],
  veryCode: [
    { required: true, message: 'Please enter the verification code.' }
  ],
  password: [
    { required: true, message: 'Please enter your password.' }
  ],
  confirmPassword: [
    { required: true, message: 'Please confirm your password.' },
    {
      validator: (value: string, cb: any) => {
        if (value !== registerForm.password) {
          cb('The passwords you entered do not match.')
        } else {
          cb()
        }
      }
    }
  ]
}

const resetRules = {
  email: [
    { required: true, message: 'Please enter your email address.' }
  ],
  veryCode: [
    { required: true, message: 'Please enter the verification code.' }
  ],
  newPassword: [
    { required: true, message: 'Please enter your new password.' }
  ]
}

// 登录处理
const handleLogin = async ({ values, errors }: any) => {
  if (errors) return
  
  loading.value = true
  try {
    const result = await userStore.login(values)
    if (result.success) {
      Message.success('Login successful.')
      visible.value = false
      isLoginMode.value = true  // 重置为登录模式
      emit('loginSuccess')
      resetForms()
    } else {
      Message.error(result.message || 'Login failed.')
    }
  } catch (error) {
    Message.error('The login request failed.')
  } finally {
    loading.value = false
  }
}

// 注册处理
const handleRegister = async ({ values, errors }: any) => {
  if (errors) return
  
  loading.value = true
  try {
    const result = await userStore.register(values)
    if (result.success) {
      Message.success('注册成功，请登录')
      isLoginMode.value = true
      resetForms()
    } else {
      Message.error(result.message || '注册失败')
    }
  } catch (error) {
    Message.error('注册请求失败')
  } finally {
    loading.value = false
  }
}

// 发送注册验证码
const sendCode = async () => {
  if (!registerForm.email) {
    Message.warning('Please enter your email address first.')
    return
  }
  
  codeLoading.value = true
  try {
    const res = await sendVerificationCodeApi({ email: registerForm.email })
    if (res.code === 0) {
      Message.success('The verification code has been sent successfully.')
      startCountdown('register')
    } else {
      Message.error(res.msg || 'The verification code failed to send.')
    }
  } catch (error: any) {
    Message.error(error.response?.data?.msg || 'The verification code failed to send.')
  } finally {
    codeLoading.value = false
  }
}

// 发送重置密码验证码
const sendResetCode = async () => {
  if (!resetForm.email) {
    Message.warning('Please enter your email address first.')
    return
  }
  
  resetCodeLoading.value = true
  try {
    const res = await sendVerificationCodeApi({ email: resetForm.email })
    if (res.code === 0) {
      Message.success('The verification code has been sent successfully.')
      startCountdown('reset')
    } else {
      Message.error(res.msg || 'The verification code failed to send.')
    }
  } catch (error: any) {
    Message.error(error.response?.data?.msg || 'The verification code failed to send.')
  } finally {
    resetCodeLoading.value = false
  }
}

// 重置密码处理
const handleResetPassword = async ({ values, errors }: any) => {
  if (errors) return
  
  resetLoading.value = true
  try {
    const res = await resetPasswordApi(values)
    if (res.code === 0) {
      Message.success('The password has been reset successfully. Please log in.')
      showForgotPassword.value = false
      resetForms()
    } else {
      Message.error(res.msg || 'The password reset failed.')
    }
  } catch (error: any) {
    Message.error(error.response?.data?.msg || 'The password reset failed.')
  } finally {
    resetLoading.value = false
  }
}

// 倒计时
const startCountdown = (type: 'register' | 'reset') => {
  const countdown = type === 'register' ? codeCountdown : resetCodeCountdown
  countdown.value = 60
  
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 切换登录/注册模式
const toggleMode = () => {
  isLoginMode.value = !isLoginMode.value
  resetForms()
}

// 重置表单
const resetForms = () => {
  loginForm.email = ''
  loginForm.password = ''
  registerForm.email = ''
  registerForm.password = ''
  registerForm.confirmPassword = ''
  registerForm.veryCode = ''
  resetForm.email = ''
  resetForm.veryCode = ''
  resetForm.newPassword = ''
}

// 取消处理
const handleCancel = () => {
  visible.value = false
  showForgotPassword.value = false
  isLoginMode.value = true  // 重置为登录模式
  resetForms()
}

const generateNickname = () => {
  registerForm.profile.nickName = generateRandomNickname()
}

const onChange = (_: any, currentFile: any) => {
  avatar.value = {
    ...currentFile,
    // url: URL.createObjectURL(currentFile.file),
  }
}
const onProgress = (currentFile: any) => {
  avatar.value = currentFile;
}

</script>

<style scoped>
</style>